package com.zhangwei.yueshijia.api;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.zhangwei.yueshijia.base.BaseApp;
import com.zhangwei.yueshijia.utils.AppConfig;
import com.zhangwei.yueshijia.utils.CacheInterceptor;
import com.zhangwei.yueshijia.utils.CookieManger;

import java.io.File;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 第一步  声明接口 声明请求的Http API
 * 第二步  实例化Retrofit对象 ,实例化声明的接口对象
 * 第三步  实例化Call对象
 * 第四步  发起请求
 * 第五步  处理返回结果
 */
public class RetrofitManager {
    private volatile static RetrofitManager singleton;
    private Retrofit retrofit;


    private RetrofitManager() {
        initRetrofit();
    }

    public static RetrofitManager getSingleton() {
        if (singleton == null) {
            synchronized (RetrofitManager.class) {
                if (singleton == null) {
                    singleton = new RetrofitManager();
                }
            }
        }
        return singleton;
    }

    public void initRetrofit() {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(UrlContants.RequestUrl.BASE_URL)
                    .client(getDefualtOkhttp())
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create(getGson()))
                    .build();
        }
    }

    private Gson getGson() {
        return new GsonBuilder()
                .serializeNulls()
                .enableComplexMapKeySerialization()
                .create();
    }

    /**
     * 开启缓存
     */
    private OkHttpClient getDefualtOkhttp() {
        return new OkHttpClient.Builder()
                //开启缓存
                .cookieJar(new CookieManger(BaseApp.getInstance()))
                .cache(getResponseCache())
                .addInterceptor(new HttpLoggingInterceptor())
                //添加缓存拦截
                .addNetworkInterceptor(new CacheInterceptor())
                .build();
    }

    //获取缓存对象

    /**
     * Android/data/包名/cache/response
     */
    public Cache getResponseCache() {
        File externalCacheDir = BaseApp.getInstance().getExternalFilesDir(AppConfig.RESPONSE_CACHE);
        return new Cache(externalCacheDir, AppConfig.DEFAULT_RESPONSE_CACHE_SIZE);
    }

    public ApiService getApiService() {
        return retrofit.create(ApiService.class);
    }


}